<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\common\model;

use buwang\base\TimeModel;
use buwang\traits\ModelTrait;
use think\facade\Validate;
use app\manage\model\User;

/**
 * 用户绑定提现信息表
 * Class Systemaccount
 * @package app\common\model
 */
class UserExtract extends TimeModel
{
    use ModelTrait;

    // 表名
    protected $name = 'user_extract';

    protected $deleteTime = false;
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'add_time';
    protected $updateTime = '';

    // 追加属性
    protected $append = [];
    public function user()
    {
        return $this->belongsTo('\app\common\model\User', 'user_id', 'id');
    }

    public function getUserList()
    {
        return \app\common\model\User::column('nickname', 'id');
    }

    /**TODO 得到用户提现信息
     * @param $user_id
     * @param $type   传了则只查相关提现信息，不传查所有
     */
    public static function getExtractInfo($user_id, $type = null)
    {
        $auth = self::where('user_id', $user_id)->where('deletetime', 0)->find();
        $status = [];
        if (!$type) {
            $status = ['bank' => [], 'alipay' => [], 'wx' => []];
            if ($auth) {
                //银行卡
                if ($auth['bank_name'] && $auth['bank_username'] && $auth['bank_zone'] && $auth['bank_detail'] && $auth['bank_card']) {

                    $status['bank'] = ['bank_name' => $auth['bank_name'], 'bank_username' => $auth['bank_username'], 'bank_zone' => $auth['bank_zone'], 'bank_detail' => $auth['bank_detail'], 'bank_card' => $auth['bank_card'], 'city_id' => $auth['city_id']];

                } else {
                    $status['bank'] = [];

                }
                //支付宝
                if ($auth['ali_name'] && $auth['aliImag'] && $auth['ali_account']) {
                    $status['alipay'] = ['ali_name' => $auth['ali_name'], 'aliImag' => $auth['aliImag'], 'ali_account' => $auth['ali_account']];
                } else {
                    $status['alipay'] = [];
                }
                //微信收款码
                if ($auth['wx_name'] && $auth['wxImag']) {
                    $status['wx'] = ['wx_name' => $auth['wx_name'], 'wxImag' => $auth['wxImag']];
                } else {
                    $status['wx'] = [];
                }

            }
        } else {
            if ($auth) {
                $status = [];
                switch ($type) {
                    case "bank":
                        //银行卡
                        if ($auth['bank_name'] && $auth['bank_username'] && $auth['bank_zone'] && $auth['bank_detail'] && $auth['bank_card']) {
                            $status = ['bank_name' => $auth['bank_name'], 'real_name' => $auth['bank_username'], 'bank_zone' => $auth['bank_zone'], 'bank_detail' => $auth['bank_detail'], 'bank_card' => $auth['bank_card'], 'city_id' => $auth['city_id']];
                        }
                        break;
                    case "alipay":
                        //支付宝
                        if ($auth['ali_name'] && $auth['aliImag'] && $auth['ali_account']) {
                            $status = ['real_name' => $auth['ali_name'], 'aliImag' => $auth['aliImag'], 'ali_account' => $auth['ali_account']];
                        }
                        break;
                    case "wx":
                        //微信收款码
                        if ($auth['wx_name'] && $auth['wxImag']) {
                            $status = ['real_name' => $auth['wx_name'], 'wxImag' => $auth['wxImag']];
                        }
                        break;
                }
            }
        }

        return $status;
    }

    /**TODO 查询用户是否存在提现方式 有1，无0
     * @param $user_id  用户id
     * @param String $flag 提现方式 不填写则拥有任意一种提现方式都返回1,填写则只查找用户是否拥有指定提现方式:bank alipay wx
     * @return int
     */
    public static function isExtractInfo($user_id, $flag = null)
    {
        $auth = self::where('user_id', $user_id)->where('deletetime', 0)->find();
        $rs = 0;
        if (!$flag) {
            if ($auth) {
                //银行卡
                if ($auth['bank_name'] && $auth['bank_username'] && $auth['bank_zone'] && $auth['bank_detail'] && $auth['bank_card']) {
                    $rs = 1;
                }
                //支付宝
                if ($auth['ali_name'] && $auth['aliImag'] && $auth['ali_account']) {
                    $rs = 1;
                }
                //微信收款码
                if ($auth['wx_name'] && $auth['wxImag']) {
                    $rs = 1;
                }
            }
        } else {
            if ($auth) {
                switch ($flag) {
                    case "bank":
                        //银行卡
                        if ($auth['bank_name'] && $auth['bank_username'] && $auth['bank_zone'] && $auth['bank_detail'] && $auth['bank_card']) {
                            $rs = 1;
                        } else {
                            $rs = 0;
                        }
                        break;
                    case "alipay":
                        //支付宝
                        if ($auth['ali_name'] && $auth['aliImag'] && $auth['ali_account']) {
                            $rs = 1;
                        } else {
                            $rs = 0;
                        }
                        break;
                    case "wx":
                        //微信收款码
                        if ($auth['wx_name'] && $auth['wxImag']) {
                            $rs = 1;
                        } else {
                            $rs = 0;
                        }
                        break;
                }

            }
        }
        return $rs;
    }


    /**提交提现信息
     * @param $user 用户
     * @param $type 绑定类型
     * @param $bank_name 银行名称
     * @param $bank_username 银行收款人姓名
     * @param $bank_zone 开户地址
     * @param $bank_detail 开户详细地址
     * @param $bank_card 银行卡号
     * @param $wx_name 微信账户人姓名
     * @param $wxImag 微信收款码
     * @param $ali_name 阿里账户人姓名
     * @param $ali_account 支付宝账号
     * @param $aliImag 支付宝收款码
     * @param $password 安全密码
     * @param bool $trans
     * @return bool
     */
    public static function bankInfo($user, $type, $bank_name = null, $bank_username = null, $bank_zone = null, $bank_detail = null, $bank_card = null, $wx_name = null, $wxImag = null, $ali_name = null, $ali_account = null, $aliImag = null, $safe_password = 0, $city_id = 0, $trans = false)
    {
        $user_id = $user['id'];//提现用户
        if (!Validate::regex($user['mobile'], "^1\d{10}$")) return self::setError('手机号不正确');
        // TODO:提现信息只提交一次，不让修改
//        if(self::isExtractInfo($user_id,$type)) return self::setError('你已绑定过此提现方式，如需修改请联系客服');

        //TODO：验证安全密码
        if (!$user['safe_password']) return self::setError('请先去设置安全密码');
        if (!password_verify(md5($safe_password), $user['safe_password'])) return self::setError('安全密码不正确');


        //绑定不同类型验证
        if ($type == 'bank') {
            //银行名称验证
            if (!preg_match('/^[\x7f-\xff]+$/', $bank_name)) return self::setError('请输入中文银行名称');
            $strLen = mb_strlen($bank_name);
            if ($strLen < 2 || $strLen > 50) return self::setError('银行名称不符或超出长度限制');
            //收款人姓名验证
            //银行名称验证
            if (!preg_match('/^[\x7f-\xff]+$/', $bank_username)) return self::setError('收款人姓名请输入中文');
            $strLen = mb_strlen($bank_username);
            if ($strLen < 2 || $strLen > 30) return self::setError('收款人姓名不符或超出长度限制');
            //开户地址验证
            $strLen = mb_strlen($bank_zone);
            if (!$bank_zone || $strLen < 2 || $strLen > 150) return self::setError('开户地址数据不存在或超出长度限制');
            //开户详细信息验证
            $strLen = mb_strlen($bank_detail);
            if (!$bank_detail || $strLen < 2 || $strLen > 150) return self::setError('详细地址数据不存在或超出长度限制');
            //银行卡号验证
            $strLen = mb_strlen($bank_card);
            if (!$bank_card || $strLen < 10 || $strLen > 20) return self::setError('银行卡号数据不存在或超出长度限制');
            $param = [
                'user_id' => $user_id,
                'bank_name' => $bank_name,
                'bank_username' => $bank_username,
                'bank_zone' => $bank_zone,
                'bank_detail' => $bank_detail,
                'bank_card' => $bank_card,
                'city_id' => $city_id
            ];
        } elseif ($type == 'alipay') {

            //阿里账户人姓名
            if (!preg_match('/^[\x7f-\xff]+$/', $ali_name)) return self::setError('收款人姓名请输入中文');
            $strLen = mb_strlen($ali_name);
            if ($strLen < 2 || $strLen > 30) return self::setError('收款人姓名不符或超出长度限制');
            //支付宝收款码
            $strLen = mb_strlen($aliImag);
            if (!$aliImag || $strLen < 2 || $strLen > 150) return self::setError('支付宝收款码未上传或路径超出长度限制');
            //支付宝账号
            $strLen = mb_strlen($ali_account);
            if (!$ali_account || $strLen < 2 || $strLen > 100) return self::setError('支付宝账号未填写或超出长度限制');

            $param = [
                'user_id' => $user_id,
                'ali_name' => $ali_name,
                'aliImag' => $aliImag,
                'ali_account' => $ali_account,
                // 'cashout_type'=>$cashout_type
            ];

        } elseif ($type == 'wx') {
            //微信账户人姓名
            if (!preg_match('/^[\x7f-\xff]+$/', $wx_name)) return self::setError('收款人姓名请输入中文');
            $strLen = mb_strlen($wx_name);
            if ($strLen < 2 || $strLen > 30) return self::setError('收款人姓名不符或超出长度限制');
            //微信收款码
            $strLen = mb_strlen($wxImag);
            if (!$wxImag || $strLen < 2 || $strLen > 150) return self::setError('微信收款码未上传或路径超出长度限制');

            $param = [
                'user_id' => $user_id,
                'wx_name' => $wx_name,
                'wxImag' => $wxImag,
                //'cashout_type'=>$cashout_type
            ];

        } else {
            return self::setError('非法提现类型');
        }
        if ($trans) {
            self::startTrans();
        }
        $res = true;
        try {
            $userExtract = self::where('user_id', $user_id)->where('deletetime', 0)->lock(true)->find();
            //提交审核
            if ($userExtract) {
                //更新
                self::where('id', $userExtract['id'])->update($param);
            } else {
                //新增
                $res = self::create($param);
            }


            $res = $res && true;

            if ($trans) {
                self::checkTrans($res);
            }
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$res) return self::setError('绑定失败');

        return $res;
    }


    /**提现
     * @param $user 提现用户
     * @param $amount 提现金额
     * @param $type 提现币种
     * @param $type 提现类型
     * @param $mark 提现备注
     * @param $safe_password 安全密码
     * @param bool $trans
     * @return bool
     */
    public static function extract($user, $amount, $balance_type, $type, $safe_password, $markInfo = '', $trans = false)
    {


        $min = bw_config('extract_money_min', 0);//最低提现金额
        $fee = bw_config('extract_money_fee', 0);//提现手续费
        //验证
        if (!$amount || $amount < 0) return self::setError('请填写提现金额');
        //TODO：验证安全密码
        if (!$user['safe_password']) return self::setError('请先去设置安全密码');

        if (!password_verify(md5($safe_password), $user['safe_password'])) return self::setError('安全密码不正确');
        $amount = floor($amount * 100) / 100;//限制最低两位
        if ($amount < $min) return self::setError('未达到最低提现金额');

        if (!$fee) {
            $fee = 0;
        } else {
            $fee = $amount * ($fee * 0.01);
        }
        $sum = $amount;//加上手续费的总提现额
        //提现方式
        switch ($balance_type) {
            case "money":
                $balance = $user['money'];//余额
                $balance_name = '余额';
                $memo = '余额提现';
                $mark = "发起余额提现申请，扣除{$balance_name}{$sum}元（包含手续费{$fee}元）";
                break;
            default:
                return self::setError('没有此提现类型');
        }
        // var_dump($markInfo);die;

        if ($sum > $balance) return self::setError("{$balance_name}不足");
        if (!in_array($type, ['bank', 'wx', 'alipay'])) return self::setError('提现方式不正确');
        //TODO 这里需要判断用户是否绑定的有这种提现方式
        if (!self::isExtractInfo($user['id'], $type)) return self::setError('你还没有绑定此提现方式');
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = true;
        try {

            //插记录
            $res1 = UserExtractLog::insertLog($user, $fee, $balance, $amount, $type, 'money', $markInfo);
            if ($res1) {
                //扣钱
                $res2 = User::changeMoney($user['id'], 0 - $sum, $memo, 'extract_sub', $mark, $res1['id']);
            }
            //判断负数
            $balance = User::getMoney($user['id']);//余额
            if ($balance < 0) {
                self::rollback();
                return self::setError("最后一次提现申请{$balance_name}不足，提交申请失败");
            }

            $res = $res && $res1 && $res2 && true;

            if ($trans) {
                self::checkTrans($res);
            }
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$res) return self::setError('提交提现申请失败');

        return $res;
    }

    /**
     * 得到列表
     */
    public static function extractList($uid, $page = 1, $limit = 10, $sort = 'id desc')
    {

        $list = self::where('user_id', '=', $uid)
            ->page($page, $limit)
            ->order($sort)
            ->select()->toArray();
        //累计充值金额
        $extract_total = self::getExtractTotal($uid);
        return ['data' => $list, 'page' => $page, 'limit' => $limit, 'extract_total' => $extract_total];

    }


    /**
     * 累计提现额度
     */
    public static function getExtractTotal($uid)
    {
        //查询已提现的总额
        $extract_price = UserExtractLog::where('user_id', $uid)
            ->where('status', '1')
            ->sum('extract_price');
        //查询已提现的总手续费
        $fee = UserExtractLog::where('user_id', $uid)
            ->where('status', '1')
            ->sum('fee');
        //总额减总手续费 = 总提现额
        $sum = bcsub($extract_price, $fee, 2);
        if ($sum < 0) $sum = 0;
        return $sum;
    }


    /**
     * 累计提现中额度
     */
    public static function getExtractingTotal($uid)
    {
        //查询提现中的总额
        $sum = UserExtractLog::where('user_id', $uid)
            ->where('status', '0')
            ->sum('extract_price');
        //总额减总手续费 = 总提现额
        if ($sum < 0) $sum = 0;
        return bcsub($sum, 0, 2);
    }

}